import React from 'react';
import './changeRolePrivilege.less';
import {Tree, Button,  Form, Popconfirm, message, Select ,Modal} from 'antd'
import config from '../../../config/config';
import $ from 'jquery';
import {browserHistory} from 'react-router';
const allRouter=config.router;
const privilegeData=config.gData;
const TreeNode = Tree.TreeNode;
const FormItem = Form.Item;
const Option = Select.Option;
const token = sessionStorage.getItem('token');
class Privilege extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            Roles: [], //用于保存角色对象
            selectedRoleId:'',//最后保存的角色Id
            gData:privilegeData,//权限列表
            checkedKeys: [], //用于保存权限key
            tree: { name: '全部权限', keyword: '0',key:'root' },
        };
    }
    componentWillMount() {
        this.getRolesList();
    }
    componentDidMount() {
        //把传过来的ID赋值给角色Id
        this.setState({
            selectedRoleId:this.props.params.roleId
        })
    }

    //获取角色列表
    getRolesList() {
        let url=allRouter.patientOrigin+'/role/list';
        $.ajax({
            url:url,
            type: "GET",
            async: true,
            headers: { Authorization: 'Bearer '+sessionStorage.getItem('token')},
            success:res=>{
                const rolesList = res.roles;
                if (rolesList.length > 0) {
                    rolesList.forEach((ele, i) => {
                        ele.index = i + 1;
                        if(ele._id===this.props.params.roleId){
                            this.setState({
                                checkedKeys:ele.tree
                            })
                        }
                    });
                }
                console.log(rolesList);
                this.setState({
                    Roles:rolesList
                })
            },
            error:err=>{
                message.config({ top: 80, });
                message.error('获取角色列表失败，请返回重新操作', 2);
            }
        });
    }
    //点击确定
    handleClick() {
        let url1=allRouter.patientOrigin+'/role/matching';
        $.ajax({
            url: url1,
            type: "post",
            async: true,
            traditional: true,
            headers: { Authorization: 'Bearer '+sessionStorage.getItem('token')},
            data: {
                id:this.state.selectedRoleId,
            },
            success:data => {
                console.log(data);
                if(data.code===200) {
                    Modal.confirm({
                        title: '更改角色权限',
                        content: '谨慎操作！权限修改会导致与该角色组关联的员工重新登录！',
                        cancelText:'取消',
                        className:'confirm-error',
                        okText:'确定',
                        onCancel: () => { },
                        onOk: () => {
                           this.changeRolePrivlege();
                        }
                    })
                }else if(data.code===201){
                    this.changeRolePrivlege();
                }
            },
            error:err=>{
                console.log(err);
            }
        });
    }
    //更改角色权限
    changeRolePrivlege(){
        let url=allRouter.patientOrigin+'/role/update';
        console.log(url);
        $.ajax({
            url: url,
            type: "post",
            async: true,
            traditional: true,
            headers: { Authorization: 'Bearer '+sessionStorage.getItem('token')},
            data: {
                id:this.state.selectedRoleId,
                tree:this.state.checkedKeys,
            },
            success:data => {
                console.log(data);
                if(data.code===200){
                    message.info('权限设置成功',);
                    browserHistory.push('roleManage');
                }else{
                    message.info('权限设置错误');
                }
            },
            error:err=>{
                console.log(err);
            }
        });
    }
    //取消保存
    cancel(e) {
        message.error('取消保存');
        browserHistory.push('roleManage');
    }
    //tree树形变化函数
    onCheck(checkedKeys, e) {
        console.log(checkedKeys);
        if(checkedKeys.length===0){
            this.setState({
                checkedKeys:[],
            });
        }else{
            this.setState({
                checkedKeys,
            });
        }
    }

    //选择角色的处理函数
    handleRoleChange(value){
        console.log(value);
        this.setState({
            selectedRoleId:value
        });
        //每次选择角色要从新调用，因为数据库更新了
        let url=allRouter.patientOrigin+'/role/list';

        $.ajax({
            url:url,
            type: "GET",
            async: true,
            headers: { Authorization: 'Bearer '+sessionStorage.getItem('token')},
            success:res=>{
                const rolesList = res.roles;
                if (rolesList.length > 0) {
                    rolesList.forEach((ele, i) => {
                        ele.index = i + 1;
                    });
                }
                this.setState({
                    Roles:rolesList
                },()=>{
                    this.state.Roles.forEach((ele, i) => {
                        if(ele._id===value){
                            this.setState({
                                checkedKeys:ele.tree
                            })
                        }
                    });
                })
            },
            error:err=>{
                message.config({ top: 80, });
                message.error('获取角色列表失败，请返回重新操作', 2);
            }
        });
    }
    render() {
        const loop = data =>
            data.map((item) => {
                if (item.son.length) {
                    return (
                        <TreeNode key={item.keyword} title={item.name}>
                            {loop(item.son)}
                        </TreeNode>
                    );
                }
                return <TreeNode key={item.keyword} title={item.name} className='finalNode' />;
            });
        const treeNodes = loop(this.state.gData);
        return (
            <div className='container'>
                <div className="box">
                        <div>
                        <div className='privilegeTitle'>
                            <h3>权限列表</h3>
                        </div>
                        <div>
                            <div>
                                <span> 选择角色：</span>
                                <Select defaultValue={this.props.params.roleName} style={{ width: 120 }} onChange={this.handleRoleChange.bind(this)}>
                                    {this.state.Roles.map(item=>{
                                        return item.name===this.props.params.roleName?<Option value={item._id} key={item._id}>{item.name}</Option>:''
                                    })}
                                </Select>
                            </div>
                            <span>{this.state.budate}</span>
                            <span>{this.state.update}</span>
                        </div>

                        <Tree
                            checkable
                            defaultExpandAll
                            onCheck={this.onCheck.bind(this)}
                            checkedKeys={this.state.checkedKeys}
                            className='privilegeTree'
                        >
                            <TreeNode key={this.state.tree.keyword} title={this.state.tree.name}>
                                {treeNodes}
                            </TreeNode>
                        </Tree>
                        <div className='privilegeBtn'>
                            <Button  onClick={this.cancel.bind(this)}>取消</Button>
                            <Button type="primary" onClick={this.handleClick.bind(this)}>保存</Button>
                        </div>
                    </div>
                </div>
            </div>
        );
    }
}
const RolePrivilegeForm = Form.create()(Privilege);
export default RolePrivilegeForm;